import React, { Component } from 'react';
import { Map, OrderedSet } from 'immutable';

import classNames from 'classnames';
import moment from 'moment';
import { orderColumns } from '../constant/columns';
import GoodsList from './goods-list.js'
import { Row, Col, Checkbox, Table, Icon, Popover, Button } from 'antd';
import { Link } from 'react-router';

import noop from 'util/noop';

export default class OrderItem extends Component {

    static defaultProps = {
        order: Map(),
        selectedRowKeys: OrderedSet(),
        selectRow: noop,
        deleteComments: noop,
        updateCommentShowState: noop
    };

    constructor(props) {
        super(props);

        this.state = {
            open: false
        }
    }

    componentDidMount() {
        // $(window).resize(this.position)
    }

    componentDidUpdate() {
        // let listWidth = $('.order-goods-list:last').width();
        // let obj = $('.list-ct:last').css('left');
        // if (!!obj && obj.indexOf(parseInt(listWidth / 2)) == -1) {
        //     $('.list-ct').css({ 'left': parseInt(listWidth / 2) });
        // }
    }
    componentWillUnmount() {
        //$(window).unbind('resize',this.position)
    }
    

    position() {
        let listWidth = $('.order-goods-list:last').width();
        $('.list-ct').css({ 'left': parseInt(listWidth / 2) });
    }

    render() {
        const { order, selectedRowKeys, selectRow } = this.props;
        const { open } = this.state;

        let disabled = !order.get('itemOrders').some(itemOrder => typeof itemOrder.get('comment') !== 'undefined')
        let consigneeName = (order.getIn(['consigneeInfo', 'consigneeName']) || '');
        const openState = classNames('order-list-item-bd', { open });
        
        let dataSource = [];
        /**
         * 保持数据统一，
         * 商品展示列和评价列都统一，这里先根据open缩减数据
         */
        if(open){
            dataSource = [order.toJS()]
        }else{
            dataSource = [order.update('itemOrders',itemOrders=>itemOrders.slice(0,1)).toJS()]
        }
        return (
            <div className="order-list-item">
                <div className="order-list-item-hd">
                    <Row>
                        <Col span={18}>
                            <Checkbox checked={selectedRowKeys.includes(order.get('tid'))} disabled={disabled} onChange={() => { selectRow(order.get('tid')) }} />
                            <div className="order-info">
                                <p>
                                    <span className="mr10">{`买家：${order.get('buyNickName')}`}</span>
                                    {consigneeName === '' ? null : <span className="mr10 t-grayer">{`收货人：${consigneeName}`}</span>}
                                    {consigneeName === '' ? null : <span className="mr10 t-grayer">{order.getIn(['consigneeInfo', 'consigneeMobile'])
                                        || order.getIn(['consigneeInfo', 'consigneePhone'])}</span>}
                                </p>
                                <p>
                                    <span className="mr10">{`订单号：${order.get('tid')}`}</span>
                                    <span className="mr10 t-grayer">{order.get('payTypeName')}</span>
                                    <span className="mr10 t-grayer">{`配送方式：${order.get('shipMethodName')}`}</span>
                                    <span className="mr10 t-grayer">{`下单时间：${moment(order.get('ctime')).format('YYYY/MM/DD HH:mm:ss')}`}</span>
                                </p>
                            </div>
                        </Col>
                        <Col span={6}>
                            <div className="t-right">

                            </div>
                        </Col>
                    </Row>
                </div>
                <div className={openState}>
                    <Table showHeader={false}
                        pagination={false}
                        columns={this.renderColumns()}
                        dataSource={dataSource} 
                    />
                    {/*
                        order.get('itemOrders').count() > 1
                            ? <a href="javascript:void(0);"><Icon className="list-ct t-grayer"
                                type={open ? 'up' : 'down'} onClick={() => this.showMore()} /></a>
                            : null
                            */
                    }
                </div>
            </div>
        )
    }


    /**
     * 列渲染
     * @returns {string|Buffer|Array.<T>|*|{options, browsertest, dist, rhino, rhinolessc}}
     */
    renderColumns() {
        let { open } = this.state;
        let { order } = this.props;
        // 追加买家评价、卖家回复
        let _orderColumns = orderColumns.slice(0);
        /**
         * 重新覆盖此函数，因为要读取父组件的open状态和商品数
         * 根据open状态显示剩余的商品
         */
        _orderColumns[0].render = (value, record, index) => {

            return {
                children: <GoodsList open={open} more={order.get('itemOrders').count() > 1} itemOrders={value} toggleMore={this.showMore} />,
                props: {
                    colSpan: 2
                }
            }
        }
        return orderColumns.concat(this.renderPrice(),this.renderComment(), this.renderReply())
    }
    renderPrice() {
        let { order } = this.props;
        return {
            title: '',
            width: 120,
            className: "ant-table-th-center va-t",
            dataIndex: 'totalTradeCash',
            render: (value, record, index) => {
            return (
                <div className="real-pay">
                <p className="total-price">&yen;{(value || 0).toFixed(2)}</p>
                <p className="freight">（含运费：&yen;{(record.logisticsFee || 0).toFixed(2)}）</p>
                <p className="goods-num">
                    共
                    {order.get('itemOrders').reduce(((sum, item) => sum + item.get('itemNumber')), 0)}
                    件
                </p>
                </div>
            )
            }
        }
    }
    renderComment() {
        return {
            title: "买家评价内容",
            width: 250,
            className: "ant-table-th-center  va-t",
            render: (v, record, index) => {
                return <div>
                    {record.itemOrders.map((itemOrder, index) => {
                        let rtDom = [<div className="evaluate-item" key={index}>
                            {itemOrder.comment ? <span href="javascript:;" onClick={e => this.showCommentDialog(itemOrder.oid)}>
                                <span className="t-pointer evaluate-content">{itemOrder.comment.content}</span>
                            </span> : <span className="t-grayer">客户还没有评价</span>}
                            {itemOrder.commentSun ? <Icon type="camera-o" className="t-primary font-20 t-pointer" onClick={e => this.showCommentDialog(itemOrder.oid)} /> : null}
                        </div>];
                        if (index == 0) {
                            return rtDom;
                        } else {
                            return [<div className="split-line" />, rtDom]
                        }
                    })}
                </div>
            }
        }
    }

    renderReply() {
        return {
            title: '操作',
            width: 270,
            key: 'orderOpt',
            className: "ant-table-th-right pr8 va-t",
            render: (value, record, index) => {
                return record.itemOrders.map((itemOrder, index) => {
                    const { comment, replies } = itemOrder;

                    let rtDom = !comment ? <div className="evaluate-item"></div> : [<div className="evaluate-item">
                        <div className="t-left evaluate-reply">
                            {replies ? replies[replies.length - 1].content : <span className="t-grayer">您还未回复</span>}
                        </div>
                        <div className="button-list">
                            <Popover trigger="hover" placement="bottom" content={<ul>{this.renderOpts(itemOrder)}</ul>}>
                                <Button type="ghost" icon="ellipsis" />
                            </Popover>
                            <Button type="primary" className="pushl" onClick={e => this.showCommentDialog(itemOrder.oid)}>回复</Button>
                        </div>
                    </div>];
                    if (index == 0) {
                        return rtDom;
                    } else {
                        return [<div className="split-line" />, rtDom]
                    }
                })
            }
        }
    }

    /**
     * 对评价的操作
     * @returns {[XML,XML]}
     */
    renderOpts(itemOrder) {
        return [
            <li><Button type="ghost" onClick={e => this.updateCommentShowState(itemOrder.comment)}>{itemOrder.comment.showState === 1 ? '前台隐藏' : '前台显示'}</Button></li>,
            <li><Button type="ghost mt8" onClick={(e) => this.deleteComment(itemOrder.oid)}>删除评价</Button></li>,
        ];
    }

    /**
     * 展示更多商品信息
     */
    showMore = () => {
        this.setState({
            open: !this.state.open
        })
    }

    showCommentDialog(oid) {
        this.props.showCommentDialog(oid);
    }

    deleteComment = (oid) => {
        this.props.deleteComment(oid)
    }

    updateCommentShowState = (comment) => {
        this.props.updateCommentShowState({
            'oid': comment.billId,
            'commentId': comment.id,
            'showState': comment.showState === 1 ? 0 : 1
        })
    }

}